import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Home from '@/views/appMain/home/Home.vue'
import Content from '@/views/appMain/home/content/Content.vue'
import useUserInfo from '@/store/useUserInfo'
import { FileType } from '@global/types'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: '/all',
    children: [
      {
        path: '/all',
        component: Content,
        meta: { title: 'all' }
      },
      {
        path: '/imgs',
        component: Content,
        meta: { title: 'imgs', fileType: FileType.image }
      },
      {
        path: '/videos',
        component: Content,
        meta: { title: 'videos', fileType: FileType.video }
      },
      {
        path: '/audios',
        component: Content,
        meta: { title: 'audios', fileType: FileType.audio }
      },
      {
        path: '/documents',
        component: Content,
        meta: { title: 'docs', fileType: FileType.document }
      }
    ]
  },
  {
    path: '/settings',
    component: () => import('@/views/appMain/settings/Settings.vue')
  },
  {
    path: '/login',
    component: () => import('@/views/appMain/login/Login.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

const whiteList = ['/login', '/settings']

router.beforeEach((to, from, next) => {
  if (to.fullPath === '/login') {
    useUserInfo().$patch({
      name: '',
      phone: '',
      token: ''
    })
    return next()
  }
  if (whiteList.includes(to.fullPath)) return next()
  const token = useUserInfo().token
  if (!token) return next('/login')
  next()
})

export default router
